package com.lswms.service.impl;

import cn.hutool.core.date.DateUtil;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.lswms.common.page.PageInfo;
import com.lswms.common.redis.RedisUtils;
import com.lswms.common.service.impl.CrudServiceImpl;
import com.lswms.common.utils.ConvertUtils;
import com.lswms.common.utils.MoneyUtil;
import com.lswms.common.utils.ZqDateUtil;
import com.lswms.dao.YnLotteryTicketResultDao;
import com.lswms.dto.YnLotteryTicketResultDTO;
import com.lswms.dto.vo.req.DoubleBallDetailReq;
import com.lswms.dto.vo.req.HistoryOpenReq;
import com.lswms.dto.vo.req.SaveDataReq;
import com.lswms.dto.vo.resp.DoubleBallDetailResp;
import com.lswms.dto.vo.resp.IndexDataResp;
import com.lswms.dto.vo.resp.NewOpenLotteryResp;
import com.lswms.dto.vo.resp.QuerySignResp;
import com.lswms.dto.vo.resp.RewardLevelResp;
import com.lswms.dto.vo.resp.TradeListResp;
import com.lswms.entity.YnLotteryTicketActivityEntity;
import com.lswms.entity.YnLotteryTicketOrderEntity;
import com.lswms.entity.YnLotteryTicketResultEntity;
import com.lswms.entity.YnPayRecordEntity;
import com.lswms.service.SysConfigService;
import com.lswms.service.YnLotteryTicketOrderService;
import com.lswms.service.YnLotteryTicketResultService;
import com.lswms.service.YnPayRecordService;
import com.lswms.service.YnUserService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * 彩票结果表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2020-06-20
 */
@Service
@Slf4j
public class YnLotteryTicketResultServiceImpl extends CrudServiceImpl<YnLotteryTicketResultDao, YnLotteryTicketResultEntity, YnLotteryTicketResultDTO> implements YnLotteryTicketResultService {

	@Autowired
	private SysConfigService sysConfigService;

    @Autowired
    private RedisUtils redisUtils;
    
	@Autowired
	private YnUserService ynUserService;
	
	@Autowired
	private YnLotteryTicketOrderService ynLotteryTicketOrderService;
	
	@Autowired
	private YnPayRecordService ynPayRecordService;

	
    @Override
    public QueryWrapper<YnLotteryTicketResultEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String ticket_no = (String)params.get("ticket_no");

        QueryWrapper<YnLotteryTicketResultEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.eq(StringUtils.isNotBlank(ticket_no), "ticket_no", ticket_no);

        return wrapper;
    }

    /**
     * 添加数据
     */
	@Override
	public void saveTicketResult(SaveDataReq req) {
		log.info("添加数据,req:{}",JSON.toJSONString(req));
		YnLotteryTicketResultEntity entity = new YnLotteryTicketResultEntity();
		entity.setOpenTime(req.getOpen_time());
		entity.setTicketNo(req.getTicket_no());
		entity.setRedBall(req.getRed_ball());
		entity.setBlueBall(req.getBlue_ball());
		if(!StringUtils.isBlank(req.getSell_amount())){
			entity.setSellAmount(MoneyUtil.convertBigDecimal(req.getSell_amount()));
		}
		if(!StringUtils.isBlank(req.getType())){
			entity.setType(Integer.parseInt(req.getType()));
		}
		entity.setCreateDate(ZqDateUtil.getNow());
		if(!StringUtils.isBlank(req.getReward_amount())){
			entity.setRewardAmount(MoneyUtil.convertBigDecimal(req.getReward_amount()));
		}
		if(!StringUtils.isBlank(req.getLevel_count1())){
			entity.setLevelCount1(Integer.parseInt(req.getLevel_count1().split("_")[0]));
			entity.setLevelAmount1(MoneyUtil.convertBigDecimal(req.getLevel_count1().split("_")[1]));
		}
		if(!StringUtils.isBlank(req.getLevel_count2())){
			entity.setLevelCount2(Integer.parseInt(req.getLevel_count2().split("_")[0]));
			entity.setLevelAmount2(MoneyUtil.convertBigDecimal(req.getLevel_count2().split("_")[1]));
		}
		if(!StringUtils.isBlank(req.getLevel_count3())){
			entity.setLevelCount3(Integer.parseInt(req.getLevel_count3().split("_")[0]));
			entity.setLevelAmount3(MoneyUtil.convertBigDecimal(req.getLevel_count3().split("_")[1]));
		}
		if(!StringUtils.isBlank(req.getLevel_count4())){
			entity.setLevelCount4(Integer.parseInt(req.getLevel_count4().split("_")[0]));
			entity.setLevelAmount4(MoneyUtil.convertBigDecimal(req.getLevel_count4().split("_")[1]));
		}
		if(!StringUtils.isBlank(req.getLevel_count5())){
			entity.setLevelCount5(Integer.parseInt(req.getLevel_count5().split("_")[0]));
			entity.setLevelAmount5(MoneyUtil.convertBigDecimal(req.getLevel_count5().split("_")[1]));
		}
		if(!StringUtils.isBlank(req.getLevel_count6())){
			entity.setLevelCount6(Integer.parseInt(req.getLevel_count6().split("_")[0]));
			entity.setLevelAmount6(MoneyUtil.convertBigDecimal(req.getLevel_count6().split("_")[1]));
		}
		baseDao.insert(entity);
		
		redisUtils.hSet("DoubleBall-"+req.getType(), req.getType(),"0");
	}

	/**
	 * 双色球、排列五详情
	 */
	@Override
	public NewOpenLotteryResp doubleBallDetail(DoubleBallDetailReq req) {
		log.info("双色球、排列五详情,req:{}",JSON.toJSONString(req));
		QueryWrapper<YnLotteryTicketResultEntity> wrapper = new QueryWrapper<YnLotteryTicketResultEntity>();
		wrapper.eq("type", req.getType());
		wrapper.orderByDesc("open_time");
		List<YnLotteryTicketResultEntity> ticket = baseDao.selectList(wrapper);
		//返回结构
		NewOpenLotteryResp resp = new NewOpenLotteryResp();
		if(ticket != null && ticket.size() > 0){
			YnLotteryTicketResultEntity entity = ticket.get(0);
			DoubleBallDetailResp dresp = queryDetail(entity);
			resp = ConvertUtils.sourceToTarget(dresp, NewOpenLotteryResp.class);
			
			List<RewardLevelResp> listResp = resultLevelMess(entity);
			resp.setList(listResp);
		}
		return resp;
	}
	/**
	 * 封装detail信息
	 * @return
	 */
	public DoubleBallDetailResp queryDetail(YnLotteryTicketResultEntity entity){
		//返回结构
		DoubleBallDetailResp resp = new DoubleBallDetailResp();
		
		String ymd = ZqDateUtil.yyyy_MM_dd(ZqDateUtil.getNow());
		//当前已开奖的
		resp.setId(entity.getId()+"");
		resp.setBlue_ball(entity.getBlueBall());
		resp.setOpen_time(entity.getOpenTime());
		resp.setRed_ball(entity.getRedBall());
		resp.setTicket_no(entity.getTicketNo());
		resp.setType(entity.getType()+"");
		String week = ZqDateUtil.dateToWeek(entity.getOpenTime());
		if(week.equals("星期一")){
			week = "Senin";
		}else if(week.equals("星期二")){
			week = "Selasa";
		}else if(week.equals("星期三")){
			week = "Rabu";
		}else if(week.equals("星期四")){
			week = "Kamis";
		}else if(week.equals("星期五")){
			week = "Jumat";
		}else if(week.equals("星期六")){
			week = "di hari Sabtu";
		}else if(week.equals("星期日")){
			week = "pada hari Minggu";
		}
		resp.setWeek(week);
		//下一期信息
		//双色球
		if(entity.getType() == 1){
			String doubleBall = sysConfigService.queryConfig("DoubleBall");
			String openTime = getDoubleBallNextOpenTime(entity.getOpenTime());
			//截止投注时间
			String stopTime = openTime.split(",")[0]+" "+doubleBall.split("_")[0];
			//开奖时间
			String openTicket = openTime.split(",")[0]+" "+doubleBall.split("_")[1];
			
			String ymd1 = openTime.split(",")[0]+"";
			if(ymd.equals(ymd1)){
				resp.setOpenLottery("1");
			}
			resp.setStop_time_next(stopTime);
			resp.setOpen_time_next(openTicket);
			resp.setReward_amount_next(queryAmount(1));
			resp.setTicket_no_next((Integer.parseInt(entity.getTicketNo()) + 1) +"");
			
			Date millDate = ZqDateUtil.getDatehms(stopTime);
			long mills = millDate.getTime() - ZqDateUtil.getNow().getTime();
			if(mills > 0){
				resp.setMills(mills+"");
			}
			//是否可投注
			if(ZqDateUtil.getNow().compareTo(ZqDateUtil.getDatehms(stopTime)) > 0){
				resp.setStatus("0");
			}
		}else if(entity.getType() == 2){
			String sort5 = sysConfigService.queryConfig("5Sort");
			String openTime = getSortNextOpenTime(entity.getOpenTime());
			//截止投注时间
			String stopTime = openTime.split(",")[0]+" "+sort5.split("_")[0];
			//开奖时间
			String openTicket = openTime.split(",")[0]+" "+sort5.split("_")[1];
			
			String ymd1 = openTime.split(",")[0]+"";
			if(ymd.equals(ymd1)){
				resp.setOpenLottery("1");
			}

			resp.setStop_time_next(stopTime);
			resp.setOpen_time_next(openTicket);
			Date millDate = ZqDateUtil.getDatehms(stopTime);
			long mills = millDate.getTime() - ZqDateUtil.getNow().getTime();
			if(mills > 0){
				resp.setMills(mills+"");
			}
			resp.setReward_amount_next(queryAmount(2));
			resp.setTicket_no_next((Integer.parseInt(entity.getTicketNo()) + 1) +"");
			//是否可投注
			if(ZqDateUtil.getNow().compareTo(ZqDateUtil.getDatehms(stopTime)) > 0){
				resp.setStatus("0");
			}
		}
		return resp;
	}
	
	/**
	 * 获取下一期开奖日期（双色球）
	 * @return
	 */
	public String getDoubleBallNextOpenTime(String preOpenTime){
	
		String openTime = "";
		for(int i = 0;i<=5;i++){
			Date now = ZqDateUtil.addDate(ZqDateUtil.getNow(),i, Calendar.DAY_OF_MONTH);
			String week = ZqDateUtil.dateToWeek(ZqDateUtil.yyyy_MM_dd(now));
			if(!preOpenTime.equals(ZqDateUtil.yyyy_MM_dd(now))){
				if(week.equals("星期二") || week.equals("星期四") || week.equals("星期日")){
					if(week.equals("星期二")){
						week = "Selasa";
					}else if(week.equals("星期四")){
						week = "Kamis";
					}else if(week.equals("星期日")){
						week = "pada hari Minggu";
					}
					openTime = ZqDateUtil.yyyy_MM_dd(now)+","+week;
					break;
				}
			}
		}
		return openTime;
	}
	/**
	 * 获取下一期开奖日期（排列五）
	 * @return
	 */
	public String getSortNextOpenTime(String preOpenTime){
	
		String openTime = "";
		for(int i = 0;i<=5;i++){
			Date now = ZqDateUtil.addDate(ZqDateUtil.getNow(),i, Calendar.DAY_OF_MONTH);
			String week = ZqDateUtil.dateToWeek(ZqDateUtil.yyyy_MM_dd(now));
			if(!preOpenTime.equals(ZqDateUtil.yyyy_MM_dd(now))){
				openTime = ZqDateUtil.yyyy_MM_dd(now)+","+week;
				break;
			}
		}
		return openTime;
	}

	/**
	 * 最新开奖
	 */
	@Override
	public List<NewOpenLotteryResp> newOpenLottery() {
		log.info("最新开奖");
		List<NewOpenLotteryResp> list = new ArrayList<NewOpenLotteryResp>();
		//查询最新开奖（双色球）
		DoubleBallDetailReq req = new DoubleBallDetailReq();
		req.setType("1");
		DoubleBallDetailResp resp = doubleBallDetail(req);
		NewOpenLotteryResp entity = ConvertUtils.sourceToTarget(resp, NewOpenLotteryResp.class);
		list.add(entity);
		//最新开奖（排列五）
		req.setType("2");
		DoubleBallDetailResp resp1 = doubleBallDetail(req);
		NewOpenLotteryResp entity1 = ConvertUtils.sourceToTarget(resp1, NewOpenLotteryResp.class);
		list.add(entity1);
		
		//查询中奖信息
		for(NewOpenLotteryResp newLottery : list){
			String id = newLottery.getId();
			YnLotteryTicketResultEntity result = baseDao.selectById(Long.parseLong(id));
			
			List<RewardLevelResp> listResp = resultLevelMess(result);
			if(listResp != null && listResp.size() >= 6){
				List<RewardLevelResp> listResp1 = new ArrayList<RewardLevelResp>();
				listResp1.add(listResp.get(0));
				listResp1.add(listResp.get(1));
				listResp = listResp1;
			}
			
			
			newLottery.setList(listResp);
		}
		return list;
	}
	
	/**
	 * 中奖等级信息
	 * @param result
	 * @return
	 */
	public List<RewardLevelResp> resultLevelMess(YnLotteryTicketResultEntity result){
		List<RewardLevelResp> listResp = new ArrayList<RewardLevelResp>();
		//双色球
		if(result.getType() == 1){
			RewardLevelResp level1 = new RewardLevelResp();
			level1.setLevel("Hadiah utama");
			level1.setLevel_count(result.getLevelCount1()+"");
			BigDecimal amount1 = result.getLevelAmount1().multiply(new BigDecimal(2500));
			level1.setLevel_reward(MoneyUtil.bigDecimal2String(amount1, 0));
			level1.setCondition("6+1");
			
			RewardLevelResp level2 = new RewardLevelResp();
			level2.setLevel("Hadiah kedua");
			level2.setLevel_count(result.getLevelCount2()+"");
			BigDecimal amount2 = result.getLevelAmount2().multiply(new BigDecimal(2500));
			level2.setLevel_reward(MoneyUtil.bigDecimal2String(amount2, 0));
			level2.setCondition("6+0");

			RewardLevelResp level3 = new RewardLevelResp();
			level3.setLevel("Hadiah ketiga");
			level3.setLevel_count(result.getLevelCount3()+"");
			BigDecimal amount3 = result.getLevelAmount3().multiply(new BigDecimal(2500));
			level3.setLevel_reward(MoneyUtil.bigDecimal2String(amount3, 0));
			level3.setCondition("5+1");

			RewardLevelResp level4 = new RewardLevelResp();
			level4.setLevel("Hadiah keempat");
			level4.setLevel_count(result.getLevelCount4()+"");
			BigDecimal amount4 = result.getLevelAmount4().multiply(new BigDecimal(2500));
			level4.setLevel_reward(MoneyUtil.bigDecimal2String(amount4, 0));
			level4.setCondition("5+0、4+1");

			RewardLevelResp level5 = new RewardLevelResp();
			level5.setLevel("Hadiah kelima");
			level5.setLevel_count(result.getLevelCount5()+"");
			BigDecimal amount5 = result.getLevelAmount5().multiply(new BigDecimal(2500));
			level5.setLevel_reward(MoneyUtil.bigDecimal2String(amount5, 0));
			level5.setCondition("4+0、3+1");

			RewardLevelResp level6 = new RewardLevelResp();
			level6.setLevel("Hadiah keenam");
			level6.setLevel_count(result.getLevelCount6()+"");
			BigDecimal amount6 = result.getLevelAmount6().multiply(new BigDecimal(2500));
			level6.setLevel_reward(MoneyUtil.bigDecimal2String(amount6, 0));
			level6.setCondition("2+1、1+1、0+1");
			
			listResp.add(level1);
			listResp.add(level2);
			listResp.add(level3);
			listResp.add(level4);
			listResp.add(level5);
			listResp.add(level6);
		}else if(result.getType() == 2){
			RewardLevelResp level1 = new RewardLevelResp();
			level1.setLevel("Hadiah utama");
			level1.setLevel_count(result.getLevelCount1()+"");
			BigDecimal amount1 = result.getLevelAmount1().multiply(new BigDecimal(2500));
			level1.setLevel_reward(MoneyUtil.bigDecimal2String(amount1, 0));
			level1.setCondition("Semua cocok");
			listResp.add(level1);
		}
		return listResp;
	}

	/**
	 * 历史开奖
	 */
	@Override
	public PageInfo<NewOpenLotteryResp> historyOpenLottery(HistoryOpenReq req) {
		log.info("历史开奖，参数req:{}",JSON.toJSONString(req));
        QueryWrapper<YnLotteryTicketResultEntity> wrapper = new QueryWrapper<>();
		wrapper.eq("type", req.getType());
		wrapper.orderByDesc("open_time");
        
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", req.getPageNo());
        params.put("limit", req.getPageSize());

		IPage<YnLotteryTicketResultEntity> pageInfo = baseDao.selectPage(getPage(params, "open_time", false),wrapper);
		
		List<NewOpenLotteryResp> list = new ArrayList<NewOpenLotteryResp>();
		for(YnLotteryTicketResultEntity entity : pageInfo.getRecords()){
			DoubleBallDetailResp resp = queryDetail(entity);
			NewOpenLotteryResp open = ConvertUtils.sourceToTarget(resp, NewOpenLotteryResp.class);
			List<RewardLevelResp> listResp = resultLevelMess(entity);
			open.setList(listResp);
			list.add(open);
		}
		
		PageInfo<NewOpenLotteryResp> pageList = new PageInfo<NewOpenLotteryResp>();
		pageList.setCount(pageInfo.getTotal());
		pageList.setList(list);
		pageList.setPageNo(Long.parseLong(req.getPageNo()));
		pageList.setPages(pageInfo.getPages());
		pageList.setPageSize(Long.parseLong(req.getPageSize()));
		log.info("历史开奖，结果:{}",JSON.toJSONString(pageList));
		return pageList;
	}

	/**
	 * 首页数据
	 */
	@Override
	public IndexDataResp indexData() {
		String banner = sysConfigService.queryConfig("Banner");
		String pic = banner.split("#")[0];
		String url = banner.split("#")[1];
		
		IndexDataResp resp = new IndexDataResp();
		List<Map<String,String>> list1 = new ArrayList<>();
		Map<String,String> map = new HashMap<String,String>();
		map.put("banner", pic);
		map.put("url", url);
		list1.add(map);
		resp.setBanner(list1);
		
		List<String> list2 = new ArrayList<String>();
		list2.add("Muhammad Novizal memenangkan 10,000rp dalam lotere");
		list2.add("Setto memenangkan 25,000rp dalam lotere");
		list2.add("Neng Tikah memenangkan 7500,000rp dalam lotere");
		list2.add("Rasto memenangkan 7500,000rp dalam lotere");
		list2.add("Akbar memenangkan 25,000rp dalam lotere");
		list2.add("DWi FAjar memenangkan 25,000rp dalam lotere");
		list2.add("Poetra Tunggal memenangkan 10,000rp dalam lotere");
		list2.add("M Rintik memenangkan 500,000rp dalam lotere");
		list2.add("Tasya Amzari memenangkan 500,000rp dalam lotere");
		list2.add("Hidoep Nina memenangkan 10,000rp dalam lotere");
		list2.add("AnidanoXXmemenangkan 25,000rp dalam lotere");
		list2.add("LianiXXmemenangkan 10,000rp dalam lotere");
		list2.add("Jorlyn AromboXXmemenangkan 25,000rp dalam lotere");
		list2.add("Putra BuanaXXmemenangkan 750,000rp dalam lotere");
		resp.setNotice(list2);
		
		/*String a1 = (String)redisUtils.hGet("DoubleBall-1", "1");
		String b1 = (String)redisUtils.hGet("DoubleBall-2", "2");

		BigDecimal aa1 = new BigDecimal(a1).multiply(new BigDecimal(2500));
		BigDecimal bb1 = new BigDecimal(b1).multiply(new BigDecimal(2500));*/
		
		resp.setDoubleBallAmount(queryAmount(1));
		resp.setPailie5Amount(queryAmount(2));
		
		String ymd = ZqDateUtil.yyyy_MM_dd(ZqDateUtil.getNow());
		//双色球
		QueryWrapper<YnLotteryTicketResultEntity> wrapper = new QueryWrapper<YnLotteryTicketResultEntity>();
		wrapper.eq("type", 1);
		wrapper.orderByDesc("open_time");
		List<YnLotteryTicketResultEntity> ticket = baseDao.selectList(wrapper);
		if(ticket != null && ticket.size() > 0){
			YnLotteryTicketResultEntity entity = ticket.get(0);
			String openTime = getDoubleBallNextOpenTime(entity.getOpenTime());
			String ymd1 = openTime.split(",")[0]+"";
			if(ymd.equals(ymd1)){
				resp.setOpenLottery("1");
			}
		}

		return resp;
	}
	
	public String queryAmount(int type){
		String a1 = (String)redisUtils.hGet("DoubleBall-"+type, type+"");
		BigDecimal aa1 = new BigDecimal(a1).multiply(new BigDecimal(2500));
		if(aa1.compareTo(new BigDecimal("10000000000")) >= 0){
			BigDecimal amount = aa1.divide(new BigDecimal("10000000000"));
			String am = MoneyUtil.bigDecimal2String(amount, 2)+"triliun";
			return am;
		}
		return MoneyUtil.bigDecimal2String(aa1, 0);
	}
	/**
	 * 每日数据
	 * @param s
	 * @param e
	 * @return
	 */
	@Override
	public Map<String, String> todayData(String s,String e) {
		if(StringUtils.isBlank(s)){
			s = ZqDateUtil.yyyy_MM_dd(ZqDateUtil.getNow());
		}
		if(StringUtils.isBlank(e)){
			e = ZqDateUtil.yyyy_MM_dd(ZqDateUtil.getNow());
		}

		String udata = ynUserService.udata(s, e);
		
		String odata = ynLotteryTicketOrderService.odata(s, e);
		
		String cdata = ynPayRecordService.cdata(s, e);


		Map<String, String> map = new HashMap<String, String>();
		map.put("tip01", udata);
		map.put("tip02", odata.split(",")[1]);
		map.put("tip03", odata.split(",")[0]);
		map.put("tip04", cdata.split(",")[1]);
		map.put("tip05", cdata.split(",")[0]);
		map.put("tip06", cdata.split(",")[2]);
		return map;
	}
}